#!/usr/sbin/rsct/perl5/bin/perl 
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 1999,2002 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
# "@(#)47   1.16   src/rsct/registry/cli/bin/joinsr.perl, srcli, rsct_rpyxh, rpyxht1f3 2/22/01 16:25:44"
######################################################################
#                                                                    #
# Module: joinsr                                                     #
#                                                                    #
# Purpose:                                                           #
#   joinsr - Performs a relational join using two System Registry    #
#            tables.                                                 #
#                                                                    #
# Syntax:                                                            #
#   joinsr [-h][-l|i|d|D Delimiter][-p First_prefix]                 #
#          [-P Second_prefix] [-s][-fr Result_table][-x][-TV]        #
#          [-c 'First_table_column...'] [-C 'Second_table_column...']#
#          key==Foreign_key First_table Second_table                 #
#          ['Selection_string']                                      #
#                                                                    #
# Flags:                                                             #
#   -h  Help. Writes this command's usage statement to stdout.       #
#   -i  Input file format. Display output in a format suitable for   #
#       use as input to mksrrow.                                     #
#   -l  Long form output. Metadata descriptions included in output.  #
#   -d Delimiter formatted output. The default delimiter is a colon  #
#       ":", use the -D flag if you wish to change the default       #
#       delimiter.                                                   #
#   -D Delimiter. Delimiter formatted output using the specified     #
#       delimiter. Use this flag to specify something other than the #
#       default colon ":", when the data to be displayed may contain #
#       colons. Use this flag to specify a one or more character     #
#       delimiter.                                                   #
#   -p First_prefix                                                  #
#       Specifies a string that is prepended to each column name from#
#       the first table. This is necessary in case there are         #
#       duplicate column names in the tables being joined.           #
#   -c 'First_table_column'                                          #
#       Names of columns from the first table to be used in the join.#
#       One or more names of columns you wish to have appear in the  #
#       result table can be specified. If more than one name is given#
#       the list must be enclosed in quotes.                         #
#   -P Second_prefix                                                 #
#       Specifies a string that is prepended to each column name from#
#       the second table. This is necessary in case there are        #
#       duplicate column names in the tables being joined.           #
#   -C 'Second_table_column'                                         #
#       Names of columns from the second table to be used in the join#
#       One or more names of columns you wish to have appear in the  #
#       result table can be specified. If more than one name is given#
#       the list must be enclosed in quotes.                         #
#   -s  Print System (SY)-qualified columns.                         #
#   -f  Force overwrite. If saving the result table (using the -r    #
#       flag, this flag forces any existing System Registry table    #
#       of the same name to be overwritten.                          #
#   -r Result_table                                                  #
#       Name of a new table to save the result of the join to. By    #
#       default the table is discarded. Result_table can be an       #
#       absolute or relative path name. The path to the target table #
#       must already exist in the System Registry.                   #
#   -x  Exclude header. Suppress header printing.                    #
#   -T  Trace. Writes this command's trace messages to stderr.       #
#   -V  Verbose. Writes this command's verbose messages to stderr.   #
#                                                                    #
# Operands:                                                          #
#  key==Foreign_key                                                  #
#               Specifies the name of a column from the first        #
#               that is type compatible with the key column of the   #
#               second table. This column is the basis for the join  #
#               of the two tables.                                   #
#  First_table  Name of the first table involved in the join. Can    #
#               contain either a relative or absolute path.          #
#  Second_table Name of the second table involved in the join. Can   #
#               contain either a relative or absolute path.          #
#  `Selection_string' Optional - Criteria to be applied to the result#
#               of the join. Only data that matches the selection    #
#               string will be returned by the System Registry to be #
#               displayed/saved.  See the srcli man page for more    #
#               information on the BNF grammar used in the selection #
#               strings.                                             #
#               Note:  The selection string must use column names    #
#               including the prefixes given (if any) because it is  #
#               being applied to the data from the two tables AFTER  #
#               the join has been completed.                         #
#                                                                    #
# Description:                                                       #
#   The joinsr command is used to perform a relational join operation#
#   on two tables, given as First_table and Second_table, producing  #
#   a new local table result table. The operation will produce a     #
#   table that is the ordered cartesian product of the Foreign_key   #
#   column in the first table and the key column of the second table.#
#   A Foreign_key column must be specified from the first table that #
#   matches the key column data type of the second table in order for#
#   the join to be performed. Since the Foreign_key column may have  #
#   duplicate values, the resulting table may have more rows that    #
#   either the first or second table. If a `Selection_string' is     #
#   given on the command line, it is applied to the resulting joined #
#   table.                                                           #
#                                                                    #
#   The columns of the resulting table must be uniquely identified,  #
#   which may not be possible if duplicate column names exist between#
#    the two tables. To avoid this problem, the caller may provide   #
#   prefixes for the column names of one or both tables by using     #
#   either of the  [-p First_prefix]or [-P Second_prefix]  flags.    #
#                                                                    #
#   By default, all columns from both the first and second table are #
#   displayed. To limit the columns in the result of the join, use   #
#   either of the flags  [-c `First_table_column ...'] or            #
#   [-C `Second_table_column ...'].                                  #
#                                                                    #
#   For a list of current column names and definitions use lssrtbldef#
#   or lssrtbl.                                                      #
#                                                                    #
#   The key column of the first table will be used as the key column #
#   of the resulting table even if it is not explicitly included in  #
#   the First_table_column list. (The new table will have a Row      #
#   Change Counter column which is initialized to zero.)             #
#                                                                    #
#    By default, the result of the join is discarded unless the      #
#   [ -r  Result_table ] flag is specified, in which case the table  #
#   is saved in the System Registry under the name Result_table. The #
#   parent directory of the Result_table must already exist in the   #
#   System Registry, or the table will not be saved.                 #
#                                                                    #
#   The result of the join is displayed by default in tabular form   #
#   using headers. Hexadecimal characters are used to display binary #
#   data. Use any of the [-l|i|d|D Delimiter][-s] and [-x] flags to  #
#   alter the output. NOTE: The [ -x ] and [ -l|i] flags can not be  #
#   used simultaneously.  If they are, the [ -x ] flag is ignored.   #
#   See the Examples section for output samples.                     #
#                                                                    #
# Exit Values:                                                       #
#   0  SR_CLI_SUCCESS        Command completed successfully.         #
#   1  SR_CLI_REGISTRY_ERROR Command terminated due to an underlying #
#                            System Registry error.                  #
#   2  SR_CLI_ERROR          Command terminated due to an underlying #
#                            error in the command script.            #
#   3  SR_CLI_BAD_OPERAND    Command terminated due to user          #
#                            specifying a bad operand.               #
#   4  SR_CLI_BAD_FLAG       Command terminated due to user          #
#                            specifying an invalid flag.             #
#   5  SR_CLI_USER_ERROR     Command terminated due to a user error. #
#                            For example specifying an undefined     #
#                            table to be joined.                     #
#                                                                    #
# Examples:                                                          #
#   1. To join information from the tables Node and Host in the      #
#   /samples directory, using the HostName primary key (assume this  #
#   is the key for both tables), enter:                              #
#       joinsr -p nd -c 'HostName NodeID' -P ht -C 'IPRoute HostName'#
#        /samples/Node /samples/Host 'nd.HostName?=c57*'             #
#       Output is:                                                   #
#           nd.HostName nd.NodeID ht.IPRoute                         #
#           c57n01      1         9.117.6.125                        #
#           c57n03      3         9.117.6.125                        #
#           c57n05      5         9.117.6.125                        #
#           ...                                                      #
#                                                                    #
#   2. To perform the same join as above with no selection string    #
#   (implies all the data is returned,) and saving the result        #
#   into the file /samples/result, enter:                            #
#       joinsr -Fr /samples/result -p nd -c 'HostName NodeID' -P ht  #
#              -C 'IPRoute HostName' /samples/Node /samples/Host     #
#                                                                    #
#   3. To display the results of the previous join in delimited      #
#   format, enter:                                                   #
#       joinsr -D :: -p nd -c 'HostName NodeID' -P ht                #
#              -C 'IPRoute HostName' /samples/Node /samples/Host     #
#                                                                    #
#--------------------------------------------------------------------#
# Inputs:                                                            #
#   from command line                                                #
#                                                                    #
# Outputs:                                                           #
#   stdout - displaying table resulting from select and help         #
#   stderr - displaying verbose, trace and error messages            #
#                                                                    #
# External Ref:                                                      #
#   Commands: $LSMSG                                                 #
#   Extensions:  CT::SR.pm CT::CT.pm CT::SRrc.pm                     #
#   Perl library routines: Getopts::Std                              #
#   SR cli library:  SR_cli_utils - initSession, isRelative,         #
#                               termSession printCEMsg,              #
#                               save_result_table,                   #
#                               open_table, set_session_variables,   #
#                               clean_session                        #
#                    SR_cli_display_utils - create_display           #
#                    SR_cli_rc.pm - CLI return codes                 #
#                                                                    #
# Tab Settings:                                                      #
#   4 and tabs should be expanded to spaces before saving this file. #
#   in vi:  (:set ts=4  and   :%!expand -4)                          #
#                                                                    #
# Change Activity:                                                   #
#   000929 HGJ 38317: Initial delivery.                              #
#                                                                    #
######################################################################

#--------------------------------------------------------------------#
#                                                                    #
# General Program Logic/Flow:                                        #
#                                                                    #
# A: Parse command line - determine selection criteria and columns   #
#    to be returned from table given.                                #
# B: Initialize session with registry, including setting the         #
#    current directory setting depending on whether an absolute or   #
#    relative table name was given.                                  #
# C: Attempt to open tables to be used in the join - report an error #
#    if unsuccessful.                                                #
# D: Call CT::SR::join - report on success or failure                #
# E: Display table information as requested OR save the table if     #
#    the [-r] flag was used, to Result_table.                        #
# F: Clean up session table and tree.                                #
#                                                                    #
#--------------------------------------------------------------------#


#--------------------------------------------------------------------#
# Included Libraries                                                 #
#--------------------------------------------------------------------#
use lib "/usr/sbin/rsct/pm";
use locale;
use Getopt::Std;

use CT::CT qw(:ct_data_type_t);
use CT_cli_utils qw(printIMsg
                    printEMsg
);

use CT::SRrc;
use CT::SR;
use SR_cli_utils qw(init_session    isRelative 
                    printCEMsg 
                    printCIMsg      save_result_table 
                    $DEFAULT_GLOBAL_MOUNT_POINT
                    open_table      clean_session
                    error_exit      set_session_variables
);
use SR_cli_display_utils qw(create_display);
use SR_cli_rc qw(:return_codes);


#--------------------------------------------------------------------#
# Global Variables                                                   #
#--------------------------------------------------------------------#
# Constants for use throughout the program
$TRUE                   = 1;
$FALSE                  = 0;

# Initialise defaults for output options 
$Opt_Long_Output        = $FALSE;       # see -l flag
$Opt_File_Output        = $FALSE;       # see -i flag
$Opt_Delimiter          = $FALSE;       # see -d, -D flags
$Opt_Print_SY           = $FALSE;       # see -s flag 
$Opt_Save_Overwrite     = $FALSE;       # see -f flag 
$Opt_Save_Result        = $FALSE;       # see -r flag
$Opt_No_Header          = $FALSE;       # see -x flag
$Trace                  = $FALSE;       # see -T flag 
$Verbose                = $FALSE;       # see -V flag

# Message Map variables
$PROGNAME               = "joinsr";
$MSGCAT                 = "srcli.cat";
$CTDIR              = "/usr/sbin/rsct";  # Cluster directory path
$CTBINDIR           = "$CTDIR/bin";      # Cluster Bin directory path
$LSMSG              = "$CTBINDIR/ctdspmsg"; # Display message routine
$ENV{'MSGMAPPATH'}  = "$CTDIR/msgmaps"; # Msg map path for $LSMSG  

%Cleanup = ();                            # Hash of items to cleanup
                                          # {Session} $session to term

#--------------------------------------------------------------------#
# Variables                                                          #
#--------------------------------------------------------------------#
# These are fed into initSession
my $Tree_handle            = CT::SR::tree_handle_t->new();

my $rc                     = 0;         # assume good return code
my $First_table            = "";        # Name of first table
my $Second_table           = "";        # name of second table
my $Foreign_key            = "";        
my $Selection_string       = "";        
my $Set_work_dir           = $FALSE;
my $Mount_point            = $DEFAULT_GLOBAL_MOUNT_POINT;
my $First_table_handle     = "";
my $Second_table_handle    = "";


#--------------------------------------------------------------------#
# Main Code                                                          #
#--------------------------------------------------------------------#
# TODO: Many verbose statements in this code will eventually by
# Trace statements when the facility is available as a Perl CLI
# (feature 48401)
# TODO: security on access to the table can not be further defined
# until after a security design has been implemented for the SR.
# ( feature 48402 ) Until then, the table is opened with the
# minimum security necessary to complete the command.
# TODO: FFDC handling will be implemented in Feature 48397.


# Parse the command line, exit if there are errors
# Error messages are handled in parse_cmd_line
($rc, $First_table, $Second_table, $Foreign_key, $Selection_string) = 
        parse_cmd_line();
($rc == 0) || error_exit($rc); 

if ($Verbose) {
    $Command_line_input = sprintf "\"  %s\n  %s\n  %s\n  %s\"",
                        $Foreign_key, $First_table,
                        $Second_table, $Selection_string;

    printIMsg("IMsgjoinsrCommandLineInput", $Command_line_input);
}


# Set up the table names depending on whether they are
# relative names or not
$holder = 0;
$holder2 = 0;
$holder3 = 0;

if ($Opt_Save_Result ne "") {
    ($holder, $Save_table_name) = 
            set_session_variables($Opt_Save_Result);
}
($holder2, $Table_one) = set_session_variables($First_table);

($holder3, $Table_two) = set_session_variables($Second_table);
if ($holder || $holder2 || $holder3) {$Set_work_dir = $TRUE;}


# Establish registry session if possible. Change current directory if 
# a relative table name given, using value set in CT_SR_HOME.
# Initialise the tree handle, blessing it into tree_handle_t class
($rc,$Tree_handle) = init_session($Set_work_dir);
($rc == 0) || error_exit($rc);

# Add the session tree handle to the cleanup hash
$Cleanup{Session} = $Tree_handle;

$Verbose && 
   printIMsg("IMsgjoinsrJoiningTables", $First_table, $Second_table);


# Open tables to be joined. If there's an error, close
# gracefully by ending the registry session and exiting.

# Open first table
($rc, $First_table_handle) = open_table($Tree_handle, $Table_one, 
                        $First_table, SR_READ);
($rc == 0) || error_exit($rc);

# Add the joined table to the cleanup hash
push @{$Cleanup{Tables}}, $First_table_handle;


# Open second table
($rc, $Second_table_handle) = open_table($Tree_handle, $Table_two, 
                        $Second_table, SR_READ);
($rc == 0) || error_exit($rc);
# Add the joined table to the cleanup hash
push @{$Cleanup{Tables}}, $Second_table_handle;


# Prepare the column names arrays for passing into CT::SR::join
if ($First_column_names =~ / /) {
        @First_cols = split / /, $First_column_names;
#        @temp = split / /, $First_column_names;
#        $First_cols = CT::SR::string_array_t->new($#temp+1);
#        $index = 0;
#        foreach (@temp) {
#            $First_cols->addEntry($index, $_);
#            $index++;
#        }               
}
else {
    $First_cols[0] = $First_column_names;
#    $First_cols = CT::SR::string_array_t->new(1);
#    $First_cols->addEntry(0, $First_column_names);
}
            
if ($Second_column_names =~ / /) {
        @Second_cols = split / /, $Second_column_names;
#        @temp = split / /, $Second_column_names;
#        $Second_cols = CT::SR::string_array_t->new($#temp+1);
#        $index = 0;
#        foreach (@temp) {
#            $Second_cols->addEntry($index, $_);
#            $index++;
#        }               
}
else {
    $Second_cols[0] = $Second_column_names;
#    $Second_cols = CT::SR::string_array_t->new(1);
#    $Second_cols->addEntry(0, $Second_column_names);
}

# At this point, I have 2 open tables. Call the join.
# it remains to be seen what the C API is going to really look like
# for implementing the columns for the tables.. string array?

$Joined_table_handle = CT::SR::table_handle_t->new;

$Verbose && print STDERR "Selection string: $Selection_string\n";

$Trace && print "Calling CT::SR::join\n";

$rc = CT::SR::join(
    $First_table_handle,$First_prefix, \@First_cols,
    scalar(@First_cols),
    $Second_table_handle, $Second_prefix, \@Second_cols,
    scalar(@Second_cols),
    $Foreign_key, $Joined_table_handle, $Selection_string
);

$Trace && print "CT::SR::join return code $rc\n";

$rc = error_check("sr_join", $rc, $First_table, $Second_table, 
    $Selection_string, $Foreign_key);
($rc == 0) || error_exit($rc);


# Add the joined table to the cleanup hash
push @{$Cleanup{Tables}}, $Joined_table_handle;

# Now figure out what to do with the result

if ($Opt_Save_Result) {
    # Use sr_move to copy the $Joined_table_handle to the
    # Result_table name.
    $rc = save_result_table($Joined_table_handle, $Save_table_name,
                $Opt_Save_Overwrite);
    ($rc == 0) || error_exit($rc);
} # end if ($Opt_Save_Result)
else {
    $Table_name = "Join Result";

    # Print output according to input flag requests
    if ($Opt_Long_Output) { 
        # Long form output
        $rc = create_display($Joined_table_handle, $Table_name, 
                "long", $Opt_Delimiter, $Opt_No_Header, 
                $Opt_Print_SY, 0);
    }
    elsif ($Opt_File_Output) { 
        # Input file format printed - one row per line
        $rc = create_display($Joined_table_handle, $Table_name, 
                "file", $Opt_Delimiter, $Opt_No_Header, 
                $Opt_Print_SY , 0); 
    }
    elsif ($Opt_Delimiter) { 
        # Delimited output       
        $rc = create_display($Joined_table_handle, $Table_name, 
                "delim", $Opt_Delimiter, $Opt_No_Header, 
                $Opt_Print_SY , 0);
    }
    else { 
        # Column output by default
        $rc = create_display($Joined_table_handle, $Table_name, 
                "column", $Opt_Delimiter, $Opt_No_Header, 
                $Opt_Print_SY , 0);
    }

} # end if ($Opt_Save_Result)


# Clean session and exit
$rc = clean_session($Tree_handle, $Mount_point, $First_table_handle,
                $Second_table_handle, $Joined_table_handle);

# Clear the cleanup hash so clean_session isn't run in error_exit
%Cleanup = ();

# Exit with the least non-zero error code
($rc == 0) || error_exit($rc);

# Return code is 0 here
exit $rc;

#--------------------------------------------------------------------#
# End Main Code                                                      #
#--------------------------------------------------------------------#


#--------------------------------------------------------------------#
# parse_cmd_line:                                                    #
#   Uses getopts to collect flags and input from command line        #
#   continuing to parse any remaining data in @ARGV. Name of tables  #
#   to join and the foreign key are passed back to the calling       #
#   program. All other data is set as global varialbes.              #
#                                                                    #
# Return values:                                                     #
#   $local_rc   - local return code                                  #
#   $table_name - name of table to be selected from                  #
#   $select_str - selection criteria                                 #
#   $return_str - list of columns to be returned by select           #
#                                                                    #
# Global Variables Altered:                                          #
#   $Opt_Long_Output   output   True (-l) request long format output #
#   $Opt_File_Output   output   True (-i) request file format output #
#   $Opt_Delimiter     output   Delimiter string (-d | -D delimitter)#
#                               When displaying output with del.     #
#   $Opt_Force_Overwrite   output   (-f) force saving result table   #
#   $Opt_Save_Result   output   True (-r) save the result table      #
#   $Opt_Print_SY      output   True (-s) print system qualified cols#
#   $Opt_No_Header     output   True (-x) print without headers.     #
#   $First_prefix      output   Prefix (-p prefix) to be added to    #
#                               first table columns.                 #
#   $Second_prefix     output   Prefix (-P prefix) to be added to    #
#                               2nd table columns.                   #
#   $First_column_names  output (-c) list of columns from 1st table  #
#   $Second_column_names output (-C) list of columns from 2nd table  #
#   $Trace             output   True (-T) turn Trace mode on.        #
#   $Verbose           output   True (-V) turn Verbose mode on.      #
#--------------------------------------------------------------------#
sub parse_cmd_line
{
# Set up local variables
my ($first_table, $second_table, $select_string, $foreign_key);
my %opts = ();

# Get input flags, if any - exit if incorrect flag given
if (getopts('hlidD:p:c:P:C:sfr:xTV', \%opts) == 0) {        
    printCEMsg("EMsgSRcliInvalidFlag");
    print_usage();
    return SR_CLI_BAD_FLAG;
}

# Help option given - ignore rest of command line 
if (defined $opts{h}) {   # print usage and exit
    print_usage();
    exit(0);
}

# Set Verbose global if requested
if (defined $opts{V}) { 
    $Verbose = $TRUE; 
}

# Dump the result table - temporary debugging flag?
if (defined $opts{T}) { 
    $Trace = $TRUE; 
}

if (defined $opts{l} && defined $opts{x}) {
    printCIMsg("IMsgSRcliLandXFlagsIncompatible");
    # TODO: not sure why doing this after reading next few lines
    # of code???
    $opts{x} = $FALSE;
}

# Suppress header printing
if (defined $opts{x}) { 
    $Opt_No_Header = $TRUE; 
}

# Print System Columns              
if (defined $opts{s}) { 
    $Opt_Print_SY = $TRUE; 
}

# Save table that results from the join
if (defined $opts{r}) { 
    if ($opts{r} == 1) { # No result_file operand
        printCEMsg("EMsgSRcliInvalidFlag");
        print_usage();
        return SR_CLI_BAD_FLAG;
    }
    $Opt_Save_Result = $opts{r}; 
}

# Overwirte existing table with saved table
if (defined $opts{f}) { 
    $Opt_Save_Overwrite = $TRUE; 
}

# Colon delimited output
if (defined $opts{d}) { 
    $Opt_Delimiter = ":";
}

# Otherwise delimited output
if (defined $opts{D}) { 
    $Opt_Delimiter = $opts{D}; 
}

# Print file formatted output, suitable for mksrrow 
if (defined $opts{i}) { 
    $Opt_File_Output = $TRUE; 
}

# Long form output
if (defined $opts{l}) { 
    $Opt_Long_Output = $TRUE;
}

# Now gather all the data for the meat of the join
# First column prefix
if (defined $opts{p}) {
    $First_prefix = $opts{p};
}

# Second column prefix
if (defined $opts{P}) {
    $Second_prefix = $opts{P};
}

# First column names 
if (defined $opts{c}) {
    $First_column_names = $opts{c};
}
else {
# TODO - this is commented out until such time as joinsr is
# put back into the C API for testing with the new selection
# string - defect 63533/feature 62387(? right feature number?)
# selection string syntax is changing, which probably means this
# value is as well.
# $First_column_names = '*';    
}

# Second column names 
if (defined $opts{C}) {
    $Second_column_names = $opts{C};
}
else {
#   $Second_column_names = '*'; 
}

if ($#ARGV < 2) {
    # Must have foreign key, first and second table left. If not,
    # quit with an error
    printEMsg("EMsgjoinsrMissingOperands");
    print_usage();
    return SR_CLI_BAD_OPERAND;
}

$foreign_key = shift @ARGV;
if ($foreign_key !~ /==/) {
    printEMsg("EMsgjoinsrBadFormatForeignKey");
    print_usage();
    return SR_CLI_BAD_OPERAND;
}
else {
    $foreign_key =~ s/.*==(.*)$/$1/;
}

$first_table = shift @ARGV;
$second_table= shift @ARGV;

# Selection string is optional
if (@ARGV) { $select_string = shift @ARGV; }
# TODO: need to test if this works with change in selection
# string grammar as of 04/24. The line should be removed after
# this date
#else {$select_string = '*'};

return (0, $first_table, $second_table, $foreign_key, $select_string);
}   # end parseCmdLine


#--------------------------------------------------------------------#
# error_check:                                                       #
#   Checks the return code from the SR function.  If an error is     #
#   detected appropriate error messages will be displayed and        #
#   SR CLI return code set.                                          #
#                                                                    #
# Parameters:                                                        #
#   $sr_function  - Name of the SR function that was called and      #
#                   whose error code we are checking.                #
#   $sr_rc        - SR function return code.                         #
#   $first_table  - Name of first table in join.                     #
#   $second_table - Name of second table to join.                    #
#   $selection_string - Selection string for join.                   #
#   $foreign_key  - Key used to join the tables.                     #
#                                                                    #
# Return values:                                                     #
#   None.                                                            #
#                                                                    #
# Global References:                                                 #
#   None.                                                            #
#--------------------------------------------------------------------#
sub error_check
{
my ($sr_function, $sr_rc, $first_table, $second_table, 
    $selection_string, $foreign_key) = @_;
my $rc = 0;

if ($sr_rc != 0) {
    if ($sr_rc == SR_NO_PERMISSION) {
        printEMsg("EMsgjoinsrNoPermission");
        $rc = SR_CLI_USER_ERROR;
    }        
    elsif ($sr_rc == SR_NO_TABLE_FIRST) {
        printCEMsg("EMsgSRcliNoTable", $first_table);   
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_KEY_EXPECTED ) {
        printEMsg("EMsgjoinsrKeyExpected");   
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_NO_TABLE_SECOND) {
        printCEMsg("EMsgSRcliNoTable", $second_table);  
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_ILLEGAL_SELECTION_STRING) {
        printCEMsg("EMsgSRcliIllegalSelectString", $selection_string); 
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_DUPLICATE_COLUMN) {
        printEMsg("EMsgjoinsrDuplicateColumns");    
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_ILLEGAL_FOREIGN_KEY) {
        printEMsg("EMsgjoinsrIllegalForeignKey", $foreign_key);
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_NO_COLUMN) {
        printEMsg("EMsgjoinsrNoColumn");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_COL_TYPE_ERROR) {
        printEMsg("EMsgjoinsrColTypeError");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_SE_UNMATCHING_PARENTHESIS) {
        printCEMsg("EMsgSRcliSEUnmatchingParen");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_SE_NO_COLUMN) {
        printCEMsg("EMsgSRcliSENoColumn");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_SE_ILLEGAL_COLUMN_NAME) {
        printCEMsg("EMsgSRcliSEIllegalColumnName");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_SE_INVALID_TYPE_VARIABLE) {
        printCEMsg("EMsgSRcliSEInavlidTypeVar");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_SE_UNMATCHING_TYPE_VARIABLE) {
        printCEMsg("EMsgSRcliSEUnmatchingTypeVar");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_SE_INVALID_OPERATOR) {
        printCEMsg("EMsgSRcliSEInvalidOperator");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_SE_INVALID_COMPARISON) {
        printCEMsg("EMsgSRcliSEInvalidComparison");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_SE_ILLEGAL_SELECTION_STRING) {
        printCEMsg("EMsgSRcliSEIllegalSS");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_SE_EXTRA_CHARS) {
        printCEMsg("EMsgSRcliSEExtraChars");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_SE_NO_VAR_PARAMETER) {
        printCEMsg("EMsgSRcliSENoVarParameter");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_SE_ILLEGAL_RANGE) {
        printCEMsg("EMsgSRcliSEIllegalRange");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_SE_ILLEGAL_RANGE_LIST) {
        printCEMsg("EMsgSRcliSEIllegalRangeList");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_SE_ILLEGAL_STRING_CONSTANT) {
        printCEMsg("EMsgSRcliSEIllegalStringConst");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_SE_NULL_STRING_CONSTANT) {
        printCEMsg("EMsgSRcliSENullStringConst");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_SE_NULL_STRING_CONSTANT) {
        printCEMsg("EMsgSRcliSENullStringConst");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_SE_ILLEGAL_NUMERIC_CONSTANT) {
        printCEMsg("EMsgSRcliSEIllegalNumericConst");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_SE_ILLEGAL_REGEX) {
        printCEMsg("EMsgSRcliSEIllegalRegex");
        $rc = SR_CLI_USER_ERROR;
    }
    else {
        printEMsg("EMsgjoinsrErrorJoiningTables", $first_table,
            $second_table, $sr_rc);
        printCEMsg("EMsgSRcliSRCommandFailure", $sr_function, $sr_rc);
        $rc = SR_CLI_REGISTRY_ERROR;
    }
}

return $rc;
}   # end error_check


#--------------------------------------------------------------------#
# print_usage : print the usage statement (syntax) to stdout.        #
#   See this command's prologue syntax section for current usage.    #
#--------------------------------------------------------------------#
sub print_usage
{
printIMsg("IMsgjoinsrUsage");
}   # end print_usage


#--------------------------------------------------------------------#
# End File                                                           #
#--------------------------------------------------------------------#
